package com.shine.commonlibrary.utils.base;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.shine.commonlibrary.R;
import com.shine.commonlibrary.utils.basemvp.BaseModel;
import com.shine.commonlibrary.utils.basemvp.BasePresenter;
import com.shine.commonlibrary.utils.baserx.RxManager;
import com.shine.commonlibrary.utils.commonwidget.LoadingDialog;
import com.shine.commonlibrary.utils.utils.LogUtils;
import com.shine.commonlibrary.utils.utils.ToastUtils;

/**
 * Created by M_genius on 2017/9/6 15:58.
 * 描述：基类 BaseFragment
 * rootView：fragment的view
 * dialog：提示对话框
 * rxManager：管理网络请求
 * 使用了懒加载方式，优化性能，需要重写loadData()加载数据
 */

public abstract class BaseFragment<T extends BasePresenter, E extends BaseModel> extends Fragment {

    protected View rootView;
    public T mPresenter;
    public E mModel;
    public RxManager mRxManager;
    public BaseActivity mActivity;

    //是否可见
    protected boolean isVisible;
    // 标志位，标志Fragment已经初始化完成。
    public boolean isPrepared = false;

    private Dialog mDialog;

    @Override
    public void onAttach(Context context) {
        mActivity = (BaseActivity) context;
        super.onAttach(context);
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (getUserVisibleHint()) {
            isVisible = true;
            onVisible();
        } else {
            isVisible = false;
            onInVisible();
        }
    }

    /**
     * fragment处于不可见状态
     */
    protected void onInVisible() {
    }

    /**
     * fragment处于可见状态
     */
    protected void onVisible() {
        //加载数据
        loadData();
    }

    /**
     * 在fragment可见时加载数据
     * 在重写loadData方法时
     */
    protected void loadData() {
        if (!isPrepared || !isVisible) {
            return;
        }
        //下面进行页面相关的数据加载操作
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(getLayoutId(), container, false);
        }
        //管理RxBus和RxJava的生命周期
        mRxManager = new RxManager();

        this.initPresenter();

        //如果使用MVP且Presenter初始化成功
        if (mPresenter != null) {
            mPresenter.mContext = this.getActivity();
        }

        isPrepared = true;
        loadData();

        return rootView;
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            //执行页面的刷新数据操作
            hideToShow();
            LogUtils.d("fragment可见");
        } else {
            LogUtils.d("fragment不可见");
        }
    }

    /**
     * 页面从hide状态转换为show状态
     * 执行页面的数据刷新操作
     */
    protected void hideToShow() {

    }

    //获取布局文件
    protected abstract int getLayoutId();

    /**
     * 简单页面无需mvp就不用管此方法即可,完美兼容各种实际场景的变通
     */
    protected void initPresenter() {

    }

    /**
     * 使一些View不可见 GONE
     *
     * @param views
     */
    protected void goneView(@NonNull View... views) {
        for (int i = 0; i < views.length; i++) {
            views[i].setVisibility(View.GONE);
        }
    }

    /**
     * 使一些View不可见 INVISIBLE
     *
     * @param views
     */
    protected void invisibleView(@NonNull View... views) {
        for (int i = 0; i < views.length; i++) {
            views[i].setVisibility(View.INVISIBLE);
        }
    }

    /**
     * 使一些View可见 VISIBLE
     *
     * @param views
     */
    protected void visibleView(@NonNull View... views) {
        for (int i = 0; i < views.length; i++) {
            views[i].setVisibility(View.VISIBLE);
        }
    }

    /**
     * 通过Class跳转界面
     **/
    public void startActivity(Class<?> cls) {
        startActivity(cls, null);
    }

    /**
     * 通过Class跳转界面
     **/
    public void startActivityForResult(Class<?> cls, int requestCode) {
        startActivityForResult(cls, null, requestCode);
    }

    /**
     * 含有Bundle通过Class跳转界面
     **/
    public void startActivityForResult(Class<?> cls, Bundle bundle, int requestCode) {
        Intent intent = new Intent();
        intent.setClass(getActivity(), cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivityForResult(intent, requestCode);
        getActivity().overridePendingTransition(R.anim.activity_right_in, R.anim.activity_left_out);
    }

    /**
     * 含有Bundle通过Class跳转界面
     **/
    public void startActivity(Class<?> cls, Bundle bundle) {
        Intent intent = new Intent();
        intent.setClass(getActivity(), cls);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        startActivity(intent);
        getActivity().overridePendingTransition(R.anim.activity_right_in, R.anim.activity_left_out);
    }


    /**
     * 开启加载进度条，默认显示 加载中。。。
     */
    public void startProgressDialog() {
        mDialog = LoadingDialog.showDialogForLoading(getActivity());
    }

    /**
     * 开启加载进度条，自定义提示信息
     *
     * @param msg
     */
    public void startProgressDialog(String msg) {
        mDialog = LoadingDialog.showDialogForLoading(getActivity(), msg, true);
    }

    /**
     * 停止加载进度条
     */
    public void stopProgressDialog() {
        if (mDialog != null) {
            mDialog.cancel();
        }
    }


    /**
     * 短暂显示Toast提示(来自String)
     **/
    public void showShortToast(String text) {
        ToastUtils.showShort(text);
    }

    /**
     * 短暂显示Toast提示(id)
     **/
    public void showShortToast(int resId) {
        ToastUtils.showShort(resId);
    }

    /**
     * 长时间显示Toast提示(来自res)
     **/
    public void showLongToast(int resId) {
        ToastUtils.showLong(resId);
    }

    /**
     * 长时间显示Toast提示(来自String)
     **/
    public void showLongToast(String text) {
        ToastUtils.showLong(text);
    }


    public void showToastWithImg(String text, int res) {
        ToastUtils.showToastWithImg(text, res);
    }

    /**
     * 网络访问错误提醒
     */
    public void showNetErrorTip() {
        ToastUtils.showToastWithImg(getText(R.string.net_error).toString(), R.drawable.icon_fail);
    }

    public void showNoNetTip() {
        ToastUtils.showToastWithImg(getText(R.string.no_net).toString(), R.drawable.icon_fail);
    }

    public void showNetErrorTip(String error) {
        ToastUtils.showToastWithImg(error, R.drawable.icon_fail);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        rootView = null;
        isPrepared = false;
        isVisible = false;
        if (mPresenter != null) {
            mPresenter.onDestroy();
        }
        mRxManager.clear();
    }
}
